package com.lookme.lmtool.view;

import com.lookme.lmtool.cracker.CrackerFactory;
import com.lookme.lmtool.cracker.filter.IFilter;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.util.Callback;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.TreeMap;

public class FilterMenu extends ContextMenu{
    /**
     * 私有构造函数
     */
    public FilterMenu(Callback<IFilter, Void> callback)
    {
        Map<String, Menu> groupMenuItem=new TreeMap<>();
        for(IFilter filter: CrackerFactory.SUPPORT_FILTER_LIST){
            if(StringUtils.isNotEmpty(filter.getGroupName())&&!groupMenuItem.containsKey(filter.getGroupName())){
                Menu menu= new Menu(filter.getGroupName());
                groupMenuItem.put(filter.getGroupName(),menu);
                getItems().add(menu);
            }
        }
        for(IFilter filter: CrackerFactory.SUPPORT_FILTER_LIST){
            MenuItem menuItem = new MenuItem(filter.getName());
            menuItem.setUserData(filter);
            menuItem.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    callback.call(filter);
                }
            });
            if(StringUtils.isNotEmpty(filter.getGroupName())&&groupMenuItem.containsKey(filter.getGroupName())) {
                groupMenuItem.get(filter.getGroupName()).getItems().add(menuItem);
            }else{
                getItems().add(menuItem);
            }
        }
    }

}